package main

import (
	"github.com/gin-gonic/gin"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"handwrite_server/bean"
	"net/http"
	"os"
)

func main() {
	CreateFolder()
	db, err := gorm.Open(mysql.Open("root:123456@tcp(127.0.0.1:3306)/handwrite?charset=utf8mb4&parseTime=True&loc=Local"), &gorm.Config{})
	if err != nil {
		println("数据库创建失败")
		return
	}
	err = db.AutoMigrate(&bean.Character{})
	if err != nil {
		return
	}
	router := gin.Default()
	router.StaticFS("/files", http.Dir("files"))
	router.POST("/upload", func(c *gin.Context) {
		file, err := c.FormFile("file")
		println(c.PostForm("character"))
		if err != nil {
			commonFailed(c, "未检测到文件", err)
		}
		err = c.SaveUploadedFile(file, "files/"+file.Filename)
		if err != nil {
			commonFailed(c, "保存文件失败", err)
		}
		var existingCharacter bean.Character
		result := db.Where(bean.Character{Character: c.PostForm("character")}).First(&existingCharacter)
		if result.Error != nil {
			chart := c.PostForm("character")
			err := writeCharacterToFile(chart)
			if err != nil {
				return
			}
			db.Create(&bean.Character{Path: "files/" + file.Filename, Character: chart})
		} else {
			err := os.Remove(existingCharacter.Path)
			if err != nil {
				return
			}
			existingCharacter.Path = "files/" + file.Filename
			db.Save(&existingCharacter)
		}
		commonSuccess(c, "上传成功", nil)
	})
	router.POST("/check", func(c *gin.Context) {
		text := c.PostForm("text")
		allText := readCharactersFromFile()
		commonSuccess(c, "检查完毕", findCharactersNotInB(text, allText))
	})
	router.POST("/getFiles", func(c *gin.Context) {
		var notFoundCharacters []gin.H
		for _, chart := range c.PostForm("text") {
			var character bean.Character
			db.Where(bean.Character{Character: string(chart)}).First(&character)
			println("emmmmmmmmmm")
			println(character.Character)
			println(character.Path)
			notFoundCharacters = append(notFoundCharacters, gin.H{
				"path":      "http://" + c.Request.Host + "/" + character.Path,
				"character": character.Character,
			})
		}
		commonSuccess(c, "获取成功", notFoundCharacters)
	})
	err = router.Run(":8080")
	if err != nil {
		return
	}
}
